import config from './config/httpConfig.js';

var request = (option, is_loading = false) => {
	var params = option.params;
	var token = uni.getStorageSync('token');
	var url = (config.IS_ONLINE ? config.DOMAIN : config.DEV_DOMAIN) + option.url;
	let ClientType = ''
	//#ifdef H5
	ClientType = 'wap'
	//#endif
	//#ifdef APP-PLUS
	ClientType = 'app'
	//#endif
	//#ifdef MP-WEIXIN
	ClientType = 'wxapp'
	//#endif
	if (is_loading) {
		uni.showLoading({
			title: 'loading...'
		})
	}
	uni.request({
		url: url,
		data: params,
		method: option.method || "POST",
		header: option.header || {
			"appid": config.APPID,
			"Authorization": token,
			"ClientType": ClientType
		},
		dataType: "json",
		responseType: "text",
		success: res => {
			if (is_loading) uni.hideLoading()
			option.success(res.data);
		},
		fail: res => {
			if (is_loading) uni.hideLoading()
			throw new Error(res);
		},
		complete: () => {
			if (is_loading) uni.hideLoading()
		}
	})
}

var login = (option) => {
	uni.login({
		success: res => {
			var params = {
				code: res.code
			}
			request({
				that: option.that,
				c: config.LOGIN_ACTION.c,
				a: config.LOGIN_ACTION.a,
				params: params,
				success: result => {
					if (result.data.code === config.SUCCESS_CODE) {
						option.that.$store.commit("upToken", result.data.data.token);
						request(option);
					} else {
						uni.showModal({
							title: "提示",
							content: result.data.msg
						});
						return false;
					}
				}
			})
		}
	})
}
//上传图片
var handlerUploadPic = (backcall) => {
	uni.chooseImage({
		count: 1,
		sizeType: ["original", "compressed"],
		sourceType: ["album", "camera"],
		success: res => {
			var tempFilePaths = res.tempFilePaths;
			uploadfile({
				tempFilePath: tempFilePaths[0],
				success: res => {
					backcall(res);
				}
			})
		}
	})
}
//上传图片视频
var handlerUploadVideo = (backcall) => {
	uni.chooseVideo({
		sourceType: [
			'album', 'camera'
		],
		compressed: true,
		maxDuration: 60,
		camera: 'back',
		success: res => {
			var tempFilePath = res.tempFilePath;
			uploadfile({
				tempFilePath: tempFilePath,
				success: res => {
					backcall(res);
				}
			})
		}
	})
}

var uploadfile = (option) => {
	uni.showLoading({
		title: "上传中..."
	});
	var url = config.IS_ONLINE ? config.UPLOAD_URL : config.DEV_UPLOAD_URL;
	uni.uploadFile({
		url: url,
		filePath: option.tempFilePath,
		header: {
			"appid": config.APPID
		},
		name: "file",
		success: result => {
			uni.hideLoading();
			var imgData = JSON.parse(result.data);
			if (imgData.code === config.SUCCESS_CODE) {
				option.success(imgData);
			} else {
				uni.showToast({
					title: '上传失败',
					icon: 'none'
				})
				option.success(false);
			}
		}
	})
}

module.exports = {
	request,
	handlerUploadPic,
	handlerUploadVideo,
}
